﻿using _111.Models;
using guidHelper;
using MyDapperApi.Models;
using MyDapperApi.Services.QywxBase;
using MyDapperApi.Services.QywxDocument.SafeRecord;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXDocument;
using System.Collections.Generic;
using static Dapper.SqlMapper;

namespace MyDapperApi.Services;

public class NetDocumentService : INetDocumentService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IQywxBaseService _qywxBaseService;
    public readonly ICsvService _csvService;
    private readonly string _qywxReceiveToken = "sdas";
    private readonly string _corpId;
    private readonly IDocSafeRecordService _docSafeRecordService;

    // 通过依赖注入获取配置，从而读取连接字符串
    public NetDocumentService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService,
        ICsvService csvService,
        IQywxBaseService qywxBaseService,
        IDocSafeRecordService docSafeRecordService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _csvService = csvService;
        _corpId = configuration["QywxSettings:CorpId"];
        _qywxBaseService = qywxBaseService;
        _docSafeRecordService = docSafeRecordService;
    }

    /// <summary>
    /// 获取企业微信文档详情
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetDocumentInfo(GetDocumentInfoRequest request)
    {
        var result = new CommonResponse();
        var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = request.docid,
            sheet_id = request.sheet_id,
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/get_fields?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                //var wxRespon = JsonConvert.DeserializeObject<AddQywxDocumentResponse>(res);
                //if (wxRespon != null && wxRespon.errmsg == "ok")
                //{
                //    result.SetSuccess();


                //}
                //else
                //{
                //    result.SetError();
                //    result.msg = res;
                //}
                result.SetSuccess(res);

                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 企业微信添加文档
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> AddDocument(AddDocumentRequest request)
    {
        var result = new CommonResponse();
        var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var temp = JsonConvert.SerializeObject(request);

        var content = new StringContent(
            JsonConvert.SerializeObject(request),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/create_doc?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<AddQywxDocumentResponse>(res);
                if (wxRespon != null && wxRespon.errmsg == "ok")
                {
                    result.SetSuccess();

                    var wxres = new QywxDocumentEntity()
                    {
                        Id = ToolHelper.GUIDTO16(),
                        DocId = wxRespon.docid,
                        DocName = request.doc_name,
                        Url = wxRespon.url,
                        Created_On = DateTime.Now,
                        Is_Deleted = 0
                    };

                    await _dateBaseService.AddBaseService<QywxDocumentEntity>(wxres);
                }
                else
                {
                    result.SetError();
                    result.msg = res;
                }
                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 基础插入数据库->智能表格
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> InsertDocument<T>(InsertDocumentRequest<T> request)//dcl1Ean315JR0ATof4Jmrhb1UUyyEFhv3kXBFyHnZ-8OfEo4iXVhnln_B-nrqVsOSXqA6bv0efFrY1hIP9VxddiQ
    {
        var result = new CommonResponse();

        var token = await _qywxBaseService.GetAccessTokenAsync(_corpId, "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var temp = JsonConvert.SerializeObject(request);

        var content = new StringContent(
            JsonConvert.SerializeObject(request),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/add_records?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<InsertDocumentResponse>(res);

                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    result.SetSuccess(wxRespon.Records);
                }
                else
                {
                    result.SetError(wxRespon.errmsg);
                }

                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 基础插入数据库->智能表格
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateDocument<T>(UpdateDocumentRequest<T> request)//dcl1Ean315JR0ATof4Jmrhb1UUyyEFhv3kXBFyHnZ-8OfEo4iXVhnln_B-nrqVsOSXqA6bv0efFrY1hIP9VxddiQ
    {
        var result = new CommonResponse();

        var token = await _qywxBaseService.GetAccessTokenAsync(_corpId, "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var temp = JsonConvert.SerializeObject(request);

        var content = new StringContent(
            JsonConvert.SerializeObject(request),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/update_records?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXResponse>(res);

                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    result.SetSuccess();
                }
                else
                {
                    result.SetError(wxRespon.errmsg);
                }

                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    #region 拉取安全巡检表格数据
    /// <summary>
    /// 执行文档数据库操作
    /// </summary>
    /// <param name="SheetId"></param>
    /// <param name="RecordId"></param>
    /// <param name="ChangeType"></param>
    /// <returns></returns>
    public async Task<CommonResponse> SelectSaveRecordChangeType(string SheetId, string RecordId, string ChangeType)
    {
        var result = new CommonResponse();

        switch (ChangeType)
        {
            case "delete_record":
                result = await _docSafeRecordService.DeleteSafeRecordDocument(RecordId);
                break;
            case "add_record":
                result = await _docSafeRecordService.UpdateSaveRecordDocument(SheetId, RecordId);
                break;
            case "update_record":
                result = await _docSafeRecordService.UpdateSaveRecordDocument(SheetId, RecordId);
                break;
        }
        return result;
    }


    //public async Task<CommonResponse> SendEmail()
    //{
    //    var result = new CommonResponse();

    //    // 邮件服务器配置（以QQ邮箱为例）
    //    string smtpServer = "smtp.163.com";
    //    int smtpPort = 587; // QQ邮箱SMTP端口
    //    string senderEmail = "a33628583@163.com"; // 发件人邮箱
    //    string senderPassword = "HDg9u3C4chjXGVhb"; // 邮箱授权码（不是登录密码）

    //    // 创建邮件发送器实例
    //    var emailSender = new EmailSender(smtpServer, smtpPort, senderEmail, senderPassword);

    //    // 发送邮件
    //    bool res = await emailSender.SendEmailWithAttachmentsAsync(
    //        toEmail: "807104555@qq.com", // 收件人邮箱
    //        subject: "测试带附件的邮件",
    //        body: "<h1>这是一封带附件的测试邮件</h1><p>请查收附件内容</p>",
    //        attachmentPaths: new[]
    //        {
    //        @"D:\File\data.csv",  // 第一个附件路径
    //        }
    //    );

    //    if (res)
    //    {
    //        result.SetSuccess("邮件发送成功");
    //    }
    //    else
    //    {
    //       result.SetError("邮件发送失败");
    //    }
    //    return result;
    //}

    #endregion

    /// <summary>
    /// 查询文档分页数据
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> PagingDocument(PagingDocumentRequest request)
    {
        var result = new CommonResponse();

        var entity = new QywxDocumentEntity();

        var dic = new Dictionary<string, string>();
        dic.Add("is_deleted", "0");

        var res = await _dateBaseService.PagingBaseService(entity, request.PageIndex.Value, request.PageSize.Value, dic);

        result.SetSuccess(res.data);

        return result;
    }
    public async Task<CommonResponse> DeleteDocument(IdRequest request)
    {
        var result = new CommonResponse();

        var entity = new QywxDocumentEntity()
        {
            Id = request.Id,
        };

        entity = await _dateBaseService.GetBaseService<QywxDocumentEntity>(entity);

        if (entity == default)
        {
            result.SetError("未查到数据");
            return result;
        }

        var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = entity.DocId,
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/del_doc?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<WXResponse>(res);
                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    entity.Is_Deleted = 1;
                    result = await _dateBaseService.UpdateSpecifiedFields<QywxDocumentEntity>(entity);
                }
                else
                {
                    result.SetError(res);
                }
                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();
        return result;
    }

    /// <summary>
    /// 获取文档角色权限信息
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public async Task<CommonResponse> GetDocAuthDetail(IdRequest request)
    {
        var result = new CommonResponse();

        var entity = new QywxDocumentEntity()
        {
            Id = request.Id,
        };

        entity = await _dateBaseService.GetBaseService<QywxDocumentEntity>(entity);

        if (entity == default)
        {
            result.SetError("未查到数据");
            return result;
        }

        var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = entity.DocId,
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var response = new HttpResponseMessage();


        response = await client.PostAsync(
        $"https://qyapi.weixin.qq.com/cgi-bin/wedoc/doc_get_auth?access_token={token}",
        content);

        if (response.IsSuccessStatusCode)
        {
            var responseStream = await response.Content.ReadAsStreamAsync();

            using (responseStream)
            {
                var res = await _qywxBaseService.StreamToStringAsync(responseStream);
                var wxRespon = JsonConvert.DeserializeObject<GetDocAuthResponse>(res);

                if (wxRespon != null && wxRespon.errcode == 0)
                {
                    var filteredItems = wxRespon.doc_member_list.Where(x => x.auth == 7).ToList();
                    
                    result.SetSuccess(filteredItems);
                }
                else
                {
                    result.SetError(res);
                }
                return result;
            }

        }
        result.SetError("与微信服务器交互失败");
        response.EnsureSuccessStatusCode();

        return result;
    }

    /// <summary>
    /// 更新文档成员标准接口
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> UpdateDocManager(UpdateDocManagerRequest request)
    {
        var result = new CommonResponse();

        var content = new StringContent(
            JsonConvert.SerializeObject(request),
            System.Text.Encoding.UTF8,
            "application/json");

        result = await _qywxBaseService.QywxDocumentPost(content, "https://qyapi.weixin.qq.com/cgi-bin/wedoc/mod_doc_member?access_token=");

        return result;
    }

    /// <summary>
    /// 更改管理员-0删除1添加
    /// </summary>
    /// <param name="request"></param>
    /// <param name="type">0删除1添加</param>
    /// <returns></returns>
    public async Task<CommonResponse> ChangeAdmin(ChangeDocumentAdminRequest request, int type)
    {
        var result = new CommonResponse();

        var entity = new QywxDocumentEntity()
        {
            Id = request.doc_id,
        };

        entity = await _dateBaseService.GetBaseService<QywxDocumentEntity>(entity);

        if (entity == default)
        {
            result.SetError("未查到数据");
            return result;
        }

        var contentList = new List<DocMemberList>();

        var opType = 0;
        if (type == 0)
        {
            opType = 1;
        }
        if (type == 1)
        {
            opType = 7;
        }

        foreach (var item in request.ids)
        {
            var temp = new DocMemberList()
            {
                type = 1,
                auth = opType,
                userid = item.Id
            };
            contentList.Add(temp);
        }

        var contentRequest = new UpdateDocManagerRequest()
        {
            docid = entity.DocId,
            update_file_member_list = contentList
        };

        var tempJson = JsonConvert.SerializeObject(contentRequest);

        result = await UpdateDocManager(contentRequest);

        return result;
    }
}